package com.badger.pattern;

import java.util.Observable;
import java.util.Observer;

/**
 * java 内置的观察者模式
 * @author liqi
 *
 */
public class TestObserverByJava {
    public static void main(String[] args) {
        Observer dog = new Observer() {
            @Override
            public void update(Observable o, Object arg) {
                System.out.println("this dog is message:" + arg);
            }
        };
        Observer cat = new Observer() {
            @Override
            public void update(Observable o, Object arg) {
                System.out.println("this cat is message:" + arg);
            }
        };
        Observer elephant = new Observer() {
            @Override
            public void update(Observable o, Object arg) {
                System.out.println("this Elephant is message:" + arg);
            }
        };

        // 创建主题
        Subjectable obs = new Subjectable();
        // 注册观察者
        obs.addObserver(dog);
        obs.addObserver(cat);
        obs.addObserver(elephant);

        for (int i = 0; i < 5; i++) {
            System.out.println("开始打招呼！");
            // 设置通知标示位
            obs.setChanged();
            obs.notifyObservers(String.format("第%s次，大家好！", i));
            try {
                Thread.sleep(5000);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
    }

    static class Subjectable extends Observable {
        @Override
        protected synchronized void setChanged() {
            super.setChanged();
        }

        @Override
        protected synchronized void clearChanged() {
            super.clearChanged();
        }
    }

}
